﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ActiveUp.Net.Mail;

namespace ETalk
{
    class GmailReader
    {
        static void Main(string[] args)
        {
            Imap4Client clnt = new Imap4Client();
            //使用ConnectSsl進行加密連線
            var hmm = clnt.ConnectSsl("imap.gmail.com", 993);
            //登入
            clnt.Login("blahblah@gmail.com", "blahblah");
            //取得收件匣
            Mailbox inbox = clnt.SelectMailbox("inbox");
            //因讀完信就會移至垃圾桶，故由後讀到前，以免序號變動
            for (int n = inbox.MessageCount; n > 0; n--)
            {
                //取回第n封信
                ActiveUp.Net.Mail.Message m = inbox.Fetch.MessageObject(n);
                //為每封郵件建立專屬資料夾(要換掉主旨不能當資料夾名稱的字元)
                string msgFolder = string.Format("{0:yyyyMMddHHmmsss}-{1}",
                    m.ReceivedDate, ReplaceInvalidPathChars(m.Subject));
                if (!Directory.Exists(msgFolder))
                    Directory.CreateDirectory(msgFolder);
                //將信件內文(HTML)寫入MailBody檔案
                string f = Path.Combine(msgFolder, "MailBody.html");
                File.WriteAllText(f, m.BodyHtml.Text);
                //逐一寫入附件檔案
                foreach (MimePart att in m.Attachments)
                {
                    f = Path.Combine(msgFolder,
                        //換掉不能當檔案名的字元
                        ReplaceInvalidFileNameChars(att.Filename));
                    File.WriteAllBytes(f, att.BinaryContent);
                }
                //將信件移至垃圾桶(CopyMessage即可產生移動資料夾的效果)
                inbox.CopyMessage(n, "[Gmail]/Trash");
                Console.WriteLine("{0}.{1}", n, m.Subject);
            }
            Console.Read();
        }
        //將不可做為路徑名稱的字元換成_
        static string ReplaceInvalidPathChars(string raw)
        {
            foreach (char c in Path.GetInvalidPathChars())
                raw = raw.Replace(c, '_');
            return raw;
        }
        //將不可做為檔案名稱的字元換成_
        static string ReplaceInvalidFileNameChars(string raw)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
                raw = raw.Replace(c, '_');
            return raw;
        }
    }
}
